package ar.edu.itba.it.pdc.configuration;

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import javax.imageio.IIOException;
import javax.imageio.ImageIO;

import org.apache.commons.lang.ArrayUtils;

public class ImageRotation {

	public static List<Byte> rotate(List<Byte> originalImage, String extension) throws IOException {
		//Okey, first, lets get a BufferedImage out of this bytes
		
		Byte[] typedBites = originalImage.toArray(new Byte[originalImage.size()]);
		byte[] primitiveBites = ArrayUtils.toPrimitive(typedBites); 
		
		BufferedImage bufferedImage = null;
		
		try {
			bufferedImage = ImageIO.read(new ByteArrayInputStream(primitiveBites));
		} catch (IIOException e) {
			return originalImage;
		}
		
		if (bufferedImage == null) {
			return originalImage;
		}
		
		//Now let's rotate it!
		
		BufferedImage rot = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
		
		AffineTransform xform = AffineTransform.getRotateInstance(Math.PI, bufferedImage.getWidth()/2, bufferedImage.getHeight()/2);
	    Graphics2D g = (Graphics2D) rot.createGraphics();
	    g.drawImage(bufferedImage, xform, null);
	    g.dispose();
	    
	    
	    
		//And lastly, back to bytes
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] imageInByte = null;
		try {
			if (!"png".equals(extension) && !"gif".equals(extension)) {
				extension = "jpeg";
			}
			ImageIO.write(rot, extension, baos);

			imageInByte = baos.toByteArray();

		} catch (IOException e) {
			return originalImage;
		}

		return new LinkedList<Byte>(Arrays.asList(ArrayUtils.toObject(imageInByte)));
	}
}
